<template>
  <div class="produce-list-container">
    <Search @searchSubmit="searchSubmitHandle" :categoryList="categoryData"></Search>
    <a-button class="add-product-btn">
      <router-link :to="{name:'AddProduct'}">新增商品</router-link>
      </a-button>
    <Table :tableData="data" :page="page"
    @changePage="changePageHandle"
    @editProduct="editProduct"
    @removeProduct="removeProduct"
    />
  </div>
</template>

<script>
import api from '@/api/category';
import Table from '@/components/Table.vue';
import Search from '../../components/Search.vue';
import tableData from '../../api/tableData';

export default {
  data() {
    return {
      data: [],
      submitForm: {},
      categoryData: {},
      page: {
        current: 1,
        pageSize: 10,
        total: 100,
        showSizeChanger: true,
      },
      categoryMap: {},
    };
  },
  async created() {
    await api.list().then((res) => {
      this.categoryData = res.data.data;
      res.data.data.forEach((i) => {
        this.categoryMap[i.id] = i;
      });
    });
    this.getTableData();
  },
  components: {
    Search,
    Table,
  },
  methods: {
    searchSubmitHandle(form) {
      this.submitForm = form;
      this.getTableData();
    },
    getTableData() {
      tableData.list({
        page: this.page.current,
        size: this.page.pageSize,
        ...this.submitForm,
      }).then((res) => {
        this.data = res.data.data.map((i) => ({
          ...i,
          categoryName: this.categoryMap[i.category].name,
        }));
        this.page.total = res.data.total;
      });
    },
    changePageHandle(page) {
      this.page = page;
      this.getTableData();
    },
    removeProduct(record) {
      this.$confirm({
        title: '确认',
        content: `确认删除${record.title}吗?`,
        okText: 'Yes',
        okType: 'danger',
        cancelText: 'No',
        onOk: () => {
          console.log('OK', record.title, '已删除');
          tableData.del(record.id).then(() => {
            this.getTableData();
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },
    editProduct(record) {
      // console.log(record);

      this.$router.push({
        name: 'EditProduct',
        params:
          {
            id: record.id,
          },
      });
    },
  },
};
</script>

<style lang="less">
.produce-list-container{
  position: relative;
}
  .add-product-btn{
    position: absolute;
    top: 3px;
    right: 10px;
  }
</style>
